package com.spirng.leetcode.day04;

public class String4 {
    public static void main(String[] args) {
        String s = reverseWords("a good   example");//blue is sky the
        System.out.println(s);
    }
    public static String reverseWords(String s) {
         int left=0;
         int right=s.length()-1;
        char[] chars = s.toCharArray();
        while (chars[right]==' '||chars[left]==' '){
             if(chars[left]==' ') left++;
             if(chars[right]==' ') right--;
         }
        String s1 = " "+s.substring(left, right + 1);
        char[] charArray = s1.toCharArray();
        right=charArray.length-1;
        int slow= charArray.length;
        String sum="";
        while (right>0){
            while (charArray[right]!=' '&&right>0) right--;
            sum+=s1.substring(right+1,slow)+" ";
            while (charArray[right]==' '&&right>0)right--;
            slow=right+1;
        }
        return sum=sum.substring(0,sum.length()-1);
    }
    public String reverseWords1(String s) {
        s = s.trim(); // 删除首尾空格
        int j = s.length() - 1, i = j;
        StringBuilder res = new StringBuilder();
        while(i >= 0) {
            while(i >= 0 && s.charAt(i) != ' ') i--; // 搜索首个空格
            res.append(s.substring(i + 1, j + 1) + " "); // 添加单词
            while(i >= 0 && s.charAt(i) == ' ') i--; // 跳过单词间空格
            j = i; // j 指向下个单词的尾字符
        }
        return res.toString().trim(); // 转化为字符串并返回
    }
}
